using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace Billing
{
    public sealed class SerDeserUtility
    {
        private static SerDeserUtility _current = new SerDeserUtility();
        private static readonly object lockObj = new object();

        private static SerDeserUtility Current
        {
            get
            {
                if (_current == null)
                {
                    _current = new SerDeserUtility();
                }
                return _current;
            }
        }

        internal T GetObject<T>(byte[] serializedBuffer, IFormatter formatter)
            where T : ISerializable
        {
            T obj = default(T);
            lock (lockObj)
            {
                using (MemoryStream stream = new MemoryStream(serializedBuffer))
                {
                    obj = (T)formatter.Deserialize(stream);
                    stream.Close();
                }
            }
            return obj;
        }

        internal byte[] GetSerializedBuffer<T>(T obj, IFormatter formatter)
            where T : ISerializable
        {
            byte[] buffer = null;
            lock (lockObj)
            {
                using (Stream stream = new MemoryStream())
                {
                    formatter.Serialize(stream, obj);
                    buffer = new byte[stream.Length];
                    stream.Seek(0, SeekOrigin.Begin);
                    stream.Read(buffer, 0, (int)stream.Length);
                    stream.Close();
                }
            }
            return buffer;
        }

        public static T GetObject<T>(byte[] serializedBuffer)
            where T : ISerializable
        {
            if (serializedBuffer == null) return default(T);
            return Current.GetObject<T>(serializedBuffer, new BinaryFormatter());
        }

        public static byte[] GetSerializedBuffer<T>(T obj)
            where T : ISerializable
        {
            if (obj == null) return null;
            return Current.GetSerializedBuffer<T>(obj, new BinaryFormatter());
        }
    }
}
